package org.hxzon.configdesigner.web.components;

import javax.inject.Inject;

import org.apache.tapestry5.Block;
import org.apache.tapestry5.ValueEncoder;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.Property;
import org.hxzon.configdesigner.core.CfgInfo;
import org.hxzon.configdesigner.core.CfgValue;
import org.hxzon.configdesigner.web.util.CfgUtil;

public class CfgRender2 {
    @Parameter
    @Property
    private CfgValue cfg;
    @Parameter
    @Property
    private boolean isNew;
    //
    @Inject
    private Block struct, list, map;
    @Inject
    private Block s, sa, i, b, r, c, e;
    @Inject
    private Block listElementIndex, mapElementIndex;
    //
    @Property
    private CfgValue value;
    @Property
    private final ValueEncoder<CfgValue> encoder = CfgUtil.encoder;

    public Object getLoopBlock() {
        CfgInfo info = value.getCfgInfo();
        int type = info.getType();
        boolean embed = info.isEmbed();
        switch (type) {
        case CfgInfo.Type_Struct:
            return embed ? struct : c;
        case CfgInfo.Type_Map:
            return embed ? map : c;
        case CfgInfo.Type_List:
            return embed ? list : c;
        case CfgInfo.Type_Boolean:
            return b;
        case CfgInfo.Type_Integer:
            return i;
        case CfgInfo.Type_Real:
            return r;
        case CfgInfo.Type_String:
            return info.isTextArea() ? sa : s;
        default:
            return e;
        }
    }

    public Object getElementIndexBlock() {
        if (value == cfg) {
            return null;
        }
        CfgValue parent = value.getParent();
        int pType = parent.getCfgInfo().getType();
        if (pType == CfgInfo.Type_List) {
            return listElementIndex;
        }
        if (pType == CfgInfo.Type_Map) {
            return mapElementIndex;
        }
        return null;
    }

    public int getIndex() {
        return value.getParent().getValues().indexOf(value);
    }

    public boolean canSubmit() {
        int type = cfg.getCfgInfo().getType();
        if (type == CfgInfo.Type_List || type == CfgInfo.Type_Map) {
            int eType = cfg.getCfgInfo().getParts().get(0).getType();
            return eType < CfgInfo.Type_Combo;
        }
        return true;
    }

    public boolean isRoot() {
        return value == cfg;
    }
}
